<?php
class Comment extends AppModel {

	var $name = 'Comment';

	//The Associations below have been created with all possible keys, those that are not needed can be removed
	var $belongsTo = array(
			'Post' =>
				array('className' => 'Post',
						'foreignKey' => 'post_id',
						'conditions' => '',
						'fields' => '',
						'order' => '',
						'counterCache' => ''
				),

			'User' =>
				array('className' => 'User',
						'foreignKey' => 'user_id',
						'conditions' => '',
						'fields' => '',
						'order' => '',
						'counterCache' => ''
				),

	);

	var $hasMany = array(
			'Vote' =>
				array('className' => 'Vote',
						'foreignKey' => 'comment_id',
						'conditions' => '',
						'fields' => array('user_id'),
						'order' => '',
						'limit' => '',
						'offset' => '',
						'dependent' => true,
						'exclusive' => '',
						'finderQuery' => '',
						'counterQuery' => ''
				),

	);

    var $validate = array(
      'text' => VALID_NOT_EMPTY,
    );

    function beforeSave()
	{
		vendor("filter");
        if(isset($this->data['Comment']['text'])) // filter comment text
				$this->data['Comment']['text'] = filtercomment($this->data['Comment']['text']);
		return true;
	}

    function beforeValidate() {
        if(isset($this->data['Comment']['text'])) $this->data['Comment']['text'] = trim($this->data['Comment']['text']);
        return true;
	}

    function hide ($id=null)
   	{
      if ($id)
      {
          $this->id = $id;
          $this->saveField('del', 1);
		  return true;
      }
   	}

    function setvote($cid,$v) {
        $this->id = $cid;
       	$this->saveField('vote', ($this->field('vote')+$v));
	}

	function getvote($cid) {
		$this->id = $cid;
		return $this->field('vote');
	}

	function getComUid($cid) {
   		$this->id = $cid;
		$this->unbindModel(array('belongsTo' => array('Post','User'), 'hasMany' => array('Vote')));
		$d=$this->read(array('user_id'));
		return $d['Comment']['user_id'];
	}

  function getauthor($cid) {
		$this->id=$cid;
		$uid=$this->field('user_id');
		$this->User->recursive=-1;
		return $this->User->read(array("id","name","email","notify"),$uid);
	}

	function fixCounts() {

    $this->execute("UPDATE users SET comcount = (SELECT COUNT(id) FROM comments WHERE comments.user_id=users.id)");
		return true;
	}

  function commentcount($cid,$dir) {
	$this->id = $cid;
   if ($dir)
     	$this->saveField('replies', ($this->field('replies')+1));
	else
			$this->saveField('replies', ($this->field('replies')-1));
	}
	
	function delByPost($pid) {
		$this->execute("DELETE FROM comments WHERE post_id=$pid");
	}

}
?>